package com.alibaba.shopping_manager_api.controller;

import com.alibaba.shopping_common.pojo.Role;
import com.alibaba.shopping_common.result.BaseResult;
import com.alibaba.shopping_common.service.RoleService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ClassName RoleController
 * @Description TODO
 * @Author Leo
 * @Date 2024/12/6 12:46
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @DubboReference
    private RoleService roleService;

    /**
     * 新增角色信息
     * @param role 角色对象
     * @return 统一对象模型
     */
    @PostMapping("/add")
    public BaseResult<Role> add(@RequestBody Role role){
        roleService.addRole(role);
        return BaseResult.OK(role);
    }

    /**
     * 根据ID删除角色
     * @param rid 角色id
     * @return 统一对象模型
     */
    @DeleteMapping("/delete")
    public BaseResult<Long> delete(Long rid){
        roleService.delRoleByID(rid);
        return BaseResult.OK(rid);
    }

    /**
     * 根据ID更新角色
     * @param role 角色对象
     * @return 统一对象模型
     */
    @PutMapping("/update")
    public BaseResult<Role> update(@RequestBody Role role){
        System.out.println("/update:"+role);
        roleService.updateRoleByID(role);
        return BaseResult.OK(role);
    }

    /**
     * 根据ID查询角色
     * @param rid 角色id
     * @return 角色信息，，包含对应的权限信息等
     */
    @GetMapping("/findById")
    public BaseResult<Role> findById(Long rid){
        Role role = roleService.findByID(rid);
        return BaseResult.OK(role);
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 页面大小
     * @return
     */
    @GetMapping("/search")
    @PreAuthorize("hasAnyAuthority('/admin/search')") // 拥有这个权限才能访问
    public BaseResult<Page<Role>> search(int page, int size){
        Page<Role> roleByPage = roleService.findRoleByPage(page, size);
        return BaseResult.OK(roleByPage);
    }

    @GetMapping("/findAll")
    public BaseResult<List<Role>> findAll(){
        List<Role> all = roleService.findAll();
        return BaseResult.OK(all);
    }

    @PutMapping("/updatePermissionToRole")
    public BaseResult updatePermissionToRole(Long rid,Long[] pids){
        roleService.updatePermissionToRole(rid,pids);
        return BaseResult.OK();
    }
}




